package com.popeye.demo.angular.service.filter;


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Configuration
public class AuthFilter {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        final FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new Filter() {

            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                final HttpServletRequest req = (HttpServletRequest) request;
                final HttpServletResponse resp = (HttpServletResponse) response;
                final String loginName = req.getHeader("Login-Name");
                final String accessToken = req.getHeader("Access-Token");
                if (Objects.equals(loginName, "yaofeng")) {
                    chain.doFilter(request, response);
                } else {
                    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                }
            }

            @Override
            public void destroy() {
            }
        });
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }
}
